﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace MergeDir
{
    class Program
    {
        static void Main()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            var opts = new MergeDirOptions();
            if (!opts.IsValid)
            {
                opts.PrintHelp();
                Environment.ExitCode = -1;
                return;
            }

            if (!opts.CheckArgument())
            {
                Environment.ExitCode = -1;
                return;
            }

            var same = 0;
            var notExist = 0;
            var diff = 0;

            try
            {
                if (Directory.Exists(opts.DiffDir))
                {
                    Console.WriteLine("正在清理Diff目录...");
                    Directory.Delete(opts.DiffDir, true);
                }
                var allFileInSource = Directory.GetFiles(opts.SourceDir, "*.*", SearchOption.AllDirectories);
                foreach (var file in allFileInSource)
                {
                    var sampleName = file.Replace(opts.SourceDir, "");
                    Console.Write($"正在比较{sampleName}...");
                    var targetFile = file.Replace(opts.SourceDir, opts.TargetDir);
                    var diffFile = file.Replace(opts.SourceDir, opts.DiffDir);
                    if (File.Exists(targetFile))
                    {
                        var sourceMd5 = GetFileMd5(file);
                        var targetMd5 = GetFileMd5(targetFile);
                        if (sourceMd5 == targetMd5)
                        {
                            same++;
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("相同");
                            Console.ForegroundColor = ConsoleColor.Gray;
                            continue;
                        }

                        diff++;
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.Write("不一致");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        if (opts.IgnoreDiff)
                        {
                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine("  已忽略");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                        else
                        {
                            Copy(diffFile, file);
                        }
                    }
                    else
                    {
                        notExist++;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write("不存在");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        Copy(diffFile, file);
                    }
                }

                Console.WriteLine();
                Console.Write($"比较结束，其中 相同：");
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.Write(same);
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write($" 不一致{(opts.IgnoreDiff ? "[已忽略]" : "")}：");

                Console.BackgroundColor = ConsoleColor.Blue;
                Console.Write(diff);
                Console.BackgroundColor = ConsoleColor.Black;

                Console.Write(" 不存在：");
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.Write(notExist);
                Console.BackgroundColor = ConsoleColor.Black;

                Console.WriteLine();

                Environment.ExitCode = 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"比较出错：{ex.Message}");
                Environment.ExitCode = -2;
            }
        }

        static void Copy(string diffFile, string file)
        {
            Console.Write("  正在复制...");
            var dirInDiff = Path.GetDirectoryName(diffFile);
            if (!Directory.Exists(dirInDiff)) Directory.CreateDirectory(dirInDiff);
            File.Copy(file, diffFile);
            Console.WriteLine("完成");
        }

        /// <summary>
        /// 获取文件的MD5 Hash值
        /// </summary>
        /// <param name="filePath">目标文件路径</param>
        /// <returns></returns>
        static string GetFileMd5(string filePath)
        {
            if (!File.Exists(filePath)) return null;
            var hash = SHA1.Create();
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] hashByte = hash.ComputeHash(stream);
                stream.Close();
                return BitConverter.ToString(hashByte).Replace("-", "");
            }
        }
    }
}
